<!-- 组件说明 -->
<template>
  <div class='params'>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>参数列表</el-breadcrumb-item>
    </el-breadcrumb> 
     <!-- 卡片视图 -->
    <el-card class="box-card">
      <!-- 警告区域 -->
      <el-alert title="注意：只允许为第三级分类设置相关参数" type="warning" show-icon :closable="true">
      </el-alert>
      <!-- 选择商品分类区域 -->
      <el-row class="cat_opt">
        <el-col>
          <span>选择商品的分类：</span>
          <!-- 商品选择级联选择框 -->
          <el-cascader v-model="cascaderCateId" :options="cascaderCateList" :props="cascaderProps" @change="cascadeCateChanged" clearable>
          </el-cascader>
        </el-col>
      </el-row>
      <!-- tap 选项卡区域 -->
      <el-tabs v-model="tapActiveName" @tab-click="handleTapClick">
        <!-- 添加动态参数面板 -->
        <el-tab-pane label="动态参数" name="many">
          <!-- 添加参数按钮 -->
          <el-button size="mini" type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog">添加参数</el-button>
          <!-- 动态参数表格 -->
          <el-table :data="dynamicParamsList" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="参数名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditParamsDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteParams(scope.row)" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <!-- 添加静态属性面板 -->
        <el-tab-pane label="静态属性" name="only">
          <el-button size="mini" type="primary" :disabled="isBtnDisabled" @click="showAddParamsDialog">添加属性</el-button>
          <!-- 静态属性表格 -->
          <el-table :data="staticParamsList" border stripe>
            <!-- 展开列 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag v-for="(item,index) in scope.row.attr_vals" :key="index" closable @close="handleClose(index,scope.row)">{{item}}</el-tag>
                <!-- 输入文本框 -->
                <el-input class="input-new-tag" v-if="scope.row.inputVisible" v-model="scope.row.inputValue" ref="saveTagInput"
                size="small" @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm(scope.row)"></el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
              </template>
            </el-table-column>
            <!-- 索引列 -->
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="属性名称" prop="attr_name"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" type="primary" @click="showEditParamsDialog(scope.row)" icon="el-icon-edit">编辑</el-button>
                <el-button size="mini" type="danger" @click="deleteParams(scope.row)" icon="el-icon-delete">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      <!-- 添加参数对话框 -->
      <el-dialog :title="title_text" :visible.sync="addParamsDialogVisible" width="40%" @close="addParamsDialogClose">
        <!-- 内容区域 -->
        <el-form :model="addParamsList" :rules="addParamsRules" ref="addParamsForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="addParamsList.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="addParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="addParams">确 定</el-button>
        </span>
      </el-dialog>
      <!-- 编辑对话框 -->
      <el-dialog :title="title_text" :visible.sync="editParamsDialogVisible" width="40%" @close="editParamsDialogClose">
        <!-- 内容区域 -->
        <el-form :model="editParamsList" :rules="addParamsRules" ref="editParamsForm" label-width="100px" class="demo-ruleForm">
          <el-form-item label="动态参数" prop="attr_name">
            <el-input v-model="editParamsList.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <!-- 底部区域 -->
        <span slot="footer" class="dialog-footer">
          <el-button @click="editParamsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="editParams">确 定</el-button>
        </span>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
  //import x from ''
  export default {
    components: {

    },
    data () {
      return {
        // 级联选择框属性
        cascaderProps:{
          label: 'cat_name',
          value: 'cat_id',
          expandTrigger: 'hover',
          children: 'children',
          checkStrictly: true
        },
        //级联选择框显示的数据
        cascaderCateList:[],
        //级联选择框选择的数据id
        cascaderCateId: [],
        // 当前活跃状态的选项卡
        tapActiveName: 'many',
        //动态参数列表
        dynamicParamsList:[],
        // 静态属性列表
        staticParamsList:[],
        //添加参数对话框显示or隐藏
        addParamsDialogVisible: false,
        //添加动态参数内容绑定
        addParamsList:{
          attr_name:'',
          attr_id: '',
          attr_sel: '',
        },
        //如果是 many 就需要填写值的选项，以逗号分隔
        attr_vals: '',
        //添加动态参数表单规则
        addParamsRules:{
          attr_name:[
            { required: true, message: '请输入动态参数', trigger: 'blur' }
          ]
        },
        ////添加参数对话框显示or隐藏
        editParamsDialogVisible: false,
        //编辑参数内容绑定
        editParamsList:{
          attr_name:'',
          attr_id: '',
          attr_sel: '',
          cat_id: ''
        },
      };
    },
    created() {
      this.getCascaderList()
    },
    computed:{
      //如果按钮需要被禁用 则返回true 否则返回false
      isBtnDisabled(){
        if(this.cascaderCateId.length !== 3){
          return true
        } else{
          return false
        }
      },
      cateId(){
        if(this.cascaderCateId.length === 3) {
          return this.cascaderCateId[2]
        }else{
          return null
        }
      },
      // 确定添加对话框显示的标题
      title_text(){
        if(this.tapActiveName === 'many') {
          return "添加动态参数"
        }else{ 
          return "添加静态属性"
        }
      }
    },
    methods: {
      //获取级联选择框中显示的数据
      async getCascaderList(){
        const{data:res} = await this.$http.get("categories")
        if(res.meta.status !== 200){
          return this.$message.error(res.meta.msg)
        }else{
          console.log(res.data);
          this.cascaderCateList = res.data
        }
      },
      //监听级联选择框数据发生改变
      cascadeCateChanged(){
        if(this.cascaderCateId.length !== 3){
          this.cascaderCateId = []
          if(this.tapActiveName === 'many'){
            this.dynamicParamsList = []
          }else{
            this.staticParamsList = []
          }
        }else{
          console.log(this.cascaderCateId);
          this.getParamsList()
        }
      },
      // 监听选项卡点击事件
      handleTapClick(){
        console.log(this.tapActiveName);
        this.getParamsList()
        if(this.tapActiveName === 'many'){

        }
      },
      //获取参数列表
      async getParamsList(){
        console.log(1);
        if(this.cascaderCateId.length === 3){
          const{data:res} = await this.$http.get(`categories/${this.cateId}/attributes`,{params:{sel: this.tapActiveName}})
          if(res.meta.status !== 200){
            return this.$message.error(res.meta.msg)
          }else{
            res.data.forEach((item) => {
              item.attr_vals = item.attr_vals ? item.attr_vals.split(','):[]
              //控制文本框的显示与隐藏
              item.inputVisible = false
              //在文本框中输入的值 
              item.inputValue = ''
            })
            this.tapActiveName == "many"?this.dynamicParamsList = res.data :this.staticParamsList = res.data 
          }
          this.addParamsList.attr_sel = this.tapActiveName
          this.addParamsList.attr_id = this.cateId
          
        }
      },
      //点击添加参数按钮 触发添加对话框显示或隐藏
      showAddParamsDialog(){
        this.addParamsDialogVisible = true
      },
      //关闭添加参数对话框 清除表单内容
      addParamsDialogClose(){
        this.$refs.addParamsForm.resetFields()
      },
      // 确定添加参数事件
      addParams(){
        this.$refs.addParamsForm.validate(async (valid) => {
          if (!valid) {
            return this.$message.error("添加动态参数出错")
          } else {
            const{data:res} = await this.$http.post(`categories/${this.cateId}/attributes`,this.addParamsList)
            if(res.meta.status !== 201) return this.$message.error(res.meta.msg)
            this.getParamsList()
            this.$message.success('添加参数成功')
            this.addParamsDialogVisible = false
          }
        })
      },
      //点击编辑按钮 触发编辑对话框显示或隐藏
      showEditParamsDialog(params){
        this.editParamsDialogVisible = true
        console.log(params);
        this.editParamsList.attr_name = params.attr_name
        this.editParamsList.attr_sel = params.attr_sel
        this.editParamsList.cat_id = params.cat_id
        this.editParamsList.attr_id = params.attr_id
      },
      //关闭添加参数对话框 清除表单内容
      editParamsDialogClose(){
        this.$refs.editParamsForm.resetFields()
      },
      // 确定添加参数事件
      editParams(){
        this.$refs.editParamsForm.validate(async (valid) => {
          if (!valid) {
            return this.$message.error("编辑参数出错")
          } else {
            const{data:res} = await this.$http.put(`categories/${this.editParamsList.cat_id}/attributes/${this.editParamsList.attr_id}`,{attr_name: this.editParamsList.attr_name,attr_sel: this.editParamsList.attr_sel})
            if(res.meta.status !== 200) return this.$message.error(res.meta.msg)
            this.getParamsList()
            this.$message.success('编辑参数成功')
            this.editParamsDialogVisible = false
          }
        })
      },
      // 删除参数
      async deleteParams(cate){
        const str = await this.$confirm('此操作将永久删除该参数, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if(str !== 'confirm'){
          return this.$message.info('已取消删除')
        }else{
          const{data:res} = await this.$http.delete(`categories/${cate.cat_id}/attributes/${cate.attr_id}`)
          if(res.meta.status !== 200) {
            return this.$message.error(res.meta.msg)
          }else{
            this.$message.success('删除成功')
            this.getParamsList()
          }
        }
      },
      //e-tag标签相关事件
      // 点击e-tag关闭icon 删除对应的参数与选项
      async handleClose(index,cate) {
        cate.attr_vals.splice(index,1)
        console.log(cate.attr_vals);
        const{data:res} = await this.$http.put(`categories/${cate.cat_id}/attributes/${cate.attr_id}`,{attr_name: cate.attr_name,attr_sel: cate.attr_sel,attr_vals: cate.attr_vals.join(',')})
        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }else{
          this.$message.success('删除成功')
          this.getParamsList()
        }
        
      },
      // 显示文本框
      showInput(cate) {
        cate.inputVisible = true;
        // nextTick方法的作用，就是当页面上元素被重新渲染之后，才会指定回调函数
        this.$nextTick(_ => {
          // 文本框自动获得焦点
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      // 按下回车键或文本框失去焦点
      async handleInputConfirm(cate) {
        console.log(cate.inputValue);
        if (cate.inputValue.trim().length === 0) {
          cate.inputValue = ''
          cate.inputVisible = false
          return 
        }
        //如果没有return 则证明输入的内容 需要做后续处理
        cate.attr_vals.push(cate.inputValue.trim())
        cate.inputValue = ''
        cate.inputVisible = false
        //发起请求 提交参数
        const{data:res} = await this.$http.put(`categories/${cate.cat_id}/attributes/${cate.attr_id}`,{attr_name: cate.attr_name,attr_sel: cate.attr_sel,attr_vals:cate.attr_vals.join(',')})
        if(res.meta.status !== 200) {
          return this.$message.error(res.meta.msg)
        }else{
          console.log(res.data);
          this.getParamsList()
          this.$message.success('添加参数成功')
        }
      }
    },
  }
</script>

<style lang='less' scoped>
//@import url()
.cat_opt{
  margin-top: 15px;
}
.el-tabs{
  margin-top: 10px;
}
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

.input-new-tag{
  widows: 150px;
}
</style>